package com.epfresh.activity;

import android.annotation.TargetApi;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.util.ArrayMap;
import android.text.ClipboardManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.ProgressBar;

import com.epfresh.R;
import com.epfresh.api.entity.RequestEntityMap;
import com.epfresh.api.entity.RequestTag;
import com.epfresh.api.entity.ResponseEntity;
import com.epfresh.api.helper.ApplicationHelper;
import com.epfresh.api.http.OnRequestListener;
import com.epfresh.api.utils.AppUtils;
import com.epfresh.api.utils.IntenetUtil;
import com.epfresh.api.utils.JsonUtils;
import com.epfresh.api.utils.T;
import com.epfresh.basedialog.ShareDialog;
import com.epfresh.bean.JsBridgeValue;
import com.epfresh.bean.StoreDetail;
import com.epfresh.constant.Constant;
import com.epfresh.fragment.WebFragment;
import com.epfresh.global.BaseActivity;
import com.epfresh.global.BaseApplication;
import com.epfresh.global.DataManager;
import com.epfresh.jsbridge.BridgeWebView;
import com.epfresh.jsbridge.BridgeWebViewClient;
import com.epfresh.wxapi.WXPayEntryActivity;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import java.util.Map;

/**
 * Created by wzh on 2016/5/6.
 */
public class WebCommonActivity extends BaseActivity {
    private BridgeWebView webview;
    private ProgressBar pb;
    private String url;
    private String title;
    private int pushType = 2;

    String imageUrl = "http://m.epfresh.com/images/icon.png";
    String titleStr = "e批课堂开课啦！";
    String description = "学用e批生鲜，采购轻松简单";


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_web);

        if (savedInstanceState != null) {
            shareUrl = getIntent().getStringExtra("share_web");
            url = savedInstanceState.getString(Constant.KEY_WEB_URL);
            title = savedInstanceState.getString(Constant.KEY_WEB_TITLE);
            pushType = savedInstanceState.getInt("pushType");
        } else {
            shareUrl = getIntent().getStringExtra("share_web");
            url = getIntent().getStringExtra(Constant.KEY_WEB_URL);
            title = getIntent().getStringExtra(Constant.KEY_WEB_TITLE);
            pushType = getIntent().getIntExtra("pushType", 2);
        }
//        if (TextUtils.isEmpty(url)) {
//            url = "https://www.sina.cn";
//        }
        if(title.equals("e批课堂")) {
            Log.e("_share_", url.substring(url.length() - 5, url.length()));
            righticon.setImageResource(R.mipmap.share_grey);
            righticon.setOnClickListener(this);
            righticon.setVisibility(View.VISIBLE);
        }
/*url 包含#_share_显示出来*/


        if(getIntent().getIntExtra("share_type",0)==1||url.contains("_share_")){
            imageUrl = "http://m.epfresh.com/images/icon.png";
            titleStr = title;
            description = getIntent().getStringExtra("share_content");
            righticon.setImageResource(R.mipmap.share_grey);
            righticon.setOnClickListener(this);
            righticon.setVisibility(View.VISIBLE);
        }

/*        if(url.substring(url.length()-5,url.length()).equals("_share_")){

        }*/
        pushType = getIntent().getIntExtra("pushType", 2);
        if (TextUtils.isEmpty(url)) {
            finish();
        } else {
            ivBack.setVisibility(View.VISIBLE);
            toolbarTitle.setVisibility(View.VISIBLE);
            toolbarTitle.setText(title == null ? "" : title);
            pb = (ProgressBar) findViewById(R.id.pb);
            webview = (BridgeWebView) findViewById(R.id.wv);
            pb.setVisibility(View.VISIBLE);
            webViewSetting();
            if(url.contains("?")){
                webview.loadUrl(url+"&oc=android");
            }else{
                webview.loadUrl(url+"?oc=android");
            }
            Log.e("urlurl___",url);
        }

    }

    public void webViewSetting() {
        WebSettings settings = webview.getSettings();
        settings.setJavaScriptEnabled(true);//启用js
        webview.addJavascriptInterface(new JsBridge(), "JSBridge");
        settings.setJavaScriptCanOpenWindowsAutomatically(true);//js和android交互
        settings.setCacheMode(WebSettings.LOAD_NO_CACHE);
//        settings.setAppCachePath(cacheDirPath); //设置缓存的指定路径
        settings.setAllowFileAccess(true); // 允许访问文件
        settings.setAppCacheEnabled(false); //设置H5的缓存打开,默认关闭
        settings.setUseWideViewPort(true);//设置webview自适应屏幕大小
        settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);//设置，可能的话使所有列的宽度不超过屏幕宽度
        settings.setLoadWithOverviewMode(true);//设置webview自适应屏幕大小
        settings.setDomStorageEnabled(true);//设置可以使用localStorage
        settings.setSupportZoom(false);//关闭zoom按钮
        settings.setBuiltInZoomControls(false);//关闭zoom
        webview.setLayerType(View.LAYER_TYPE_SOFTWARE, null);

        webview.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                if (newProgress > 99) {
                    pb.setVisibility(View.GONE);
                } else {
                    if (pb.getVisibility() == View.GONE)
                        pb.setVisibility(View.VISIBLE);
                    pb.setProgress(newProgress);
                }
                super.onProgressChanged(view, newProgress);
            }

            @Override
            public void onReceivedTitle(WebView view, String title) {
                if (title != null && !"".equals(title))
//                    toolbarTitle.setText(title);
                view.getUrl();
                Log.e("getUrl", view.getUrl());
            }
        });
        webview.setWebViewClient(new BridgeWebViewClient(webview) {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                if (url != null && url.startsWith("epfreshbuyerclick://product") && mContext != null) {
                    Intent intent = new Intent(mContext, DetailGoodsActivity.class);
                    String id = Uri.parse(url).getQueryParameter("id");
                    int serviceStoreId = Integer.parseInt(Uri.parse(url).getQueryParameter("serviceStoreId"));
                    intent.putExtra("storeId", Uri.parse(url).getQueryParameter("storeId"));
                    intent.putExtra("id", id);
                    intent.putExtra("serviceStoreId", serviceStoreId);
                    startActivity(intent);
                    return true;
                }else if (url != null && url.startsWith("epfreshbuyerclick://servicephone") && mContext != null) {
                    String phone = Uri.parse(url).getQueryParameter("phone");
                    ClipboardManager cm = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
                    // 将文本内容放到系统剪贴板里。
                    cm.setText(phone);
                    Intent intent = new Intent();
                    ComponentName cmp = new ComponentName(" com.tencent.mm ","com.tencent.mm.ui.LauncherUI");
                    intent.setAction(Intent.ACTION_MAIN);
                    intent.addCategory(Intent.CATEGORY_LAUNCHER);
                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    intent.setComponent(cmp);
                    return true;
                }else if (url != null && url.startsWith("epfreshbuyerclick://promotionproduct") && mContext != null) {
                    Intent intent = new Intent(mContext, DetailGoodsActivity.class);
                    String id = Uri.parse(url).getQueryParameter("id");
                    String promotionId = Uri.parse(url).getQueryParameter("promotionid");
                    int serviceStoreId = Integer.parseInt(Uri.parse(url).getQueryParameter("serviceStoreId"));
                    intent.putExtra("id", id);
                    intent.putExtra("storeId", Uri.parse(url).getQueryParameter("storeId"));
                    intent.putExtra("promotionItemId",promotionId);
                    intent.putExtra("serviceStoreId", serviceStoreId);
                    startActivity(intent);
                    return true;
                }else if (url != null && url.startsWith("epfreshbuyerclick://store") && mContext != null) {
//                    SalesType=1整货,SalesType=2散货
                    String salesType = Uri.parse(url).getQueryParameter("salestype");
                    if ("2".equals(salesType)) {
                        requestDc(false,Uri.parse(url).getQueryParameter("id"));
                    } else {
                        String id = Uri.parse(url).getQueryParameter("id");
                        Intent intent = new Intent(mContext, CommonStoreActivity.class);
                        intent.putExtra("storeId", id);
                        startActivity(intent);
                    }
                    return true;
                } else if (url != null && url.startsWith("epfreshbuyerclick://minus") && mContext != null) {
                    Intent intent = new Intent(mContext, OrderMinusRecordActivity.class);
                    String id = Uri.parse(url).getQueryParameter("id");
                    intent.putExtra("id", id);
                    startActivity(intent);
                    Log.e(")________fadsf____", id);

                    return true;
                } else if (url != null && url.startsWith("epfreshbuyerclick://assess") && mContext != null) {
                    Intent evaluate = new Intent(mContext, CommentNewActivity.class);
                    String id = Uri.parse(url).getQueryParameter("id");
                    evaluate.putExtra("orderId", id);
                    startActivityForResult(evaluate,0x001);
                    Log.e(")________fadsf____", id);

                    return true;
                } else if (url != null && url.startsWith("epfreshbuyerclick://order") && mContext != null) {
                    Intent intent = new Intent(mContext, OrderLogisticsInfoActivity.class);
                    String id = Uri.parse(url).getQueryParameter("id");
                    intent.putExtra("logisticsNo", id);
                    startActivity(intent);
                    Log.e(")_____________________", id);
                    return true;
                } else if (url != null && url.startsWith("tel:")) {//电话
                    Intent intent = new Intent(Intent.ACTION_VIEW,
                            Uri.parse(url));
                    startActivity(intent);
                    return true;
                } else if (url != null && url.startsWith("epfreshbuyerclick://pay")) {//直接支付
                    Intent pay = new Intent(mContext, WXPayEntryActivity.class);
                    pay.putExtra("payWay", 1);
                    String orderId = Uri.parse(url).getQueryParameter("id");
                    pay.putExtra("orderId", orderId);
                    startActivity(pay);
                    return true;
                } else if (url != null && url.startsWith("epfreshbuyerclick://surepay")) {//确认收货,有尾款
                    Intent pay = new Intent(mContext, WXPayEntryActivity.class);
                    String orderId = Uri.parse(url).getQueryParameter("id");
                    pay.putExtra("orderId", orderId);
                    pay.putExtra("type", "2");
                    startActivity(pay);
                    return true;
                } else if (url != null && url.startsWith("epfreshbuyerclick://again")) {
                    Intent intent = new Intent(mContext,
                            HomeActivity.class);
                    intent.putExtra("home_tab_index", 2);
                    DataManager.getInstance().isNeedRefreshCart = true;
                    startActivity(intent);

                    return true;
                } /*else if (url != null && url.startsWith("epfreshbuyerclick://notify")) {//通知更新
                    isRefresh = true;
                    return true;
                }*/ else if (url != null && url.startsWith("epfreshbuyerclick://loginexc")) {//登陆异常
                    Intent intent = new Intent(mContext, LoginActivity.class);
                    intent.putExtra("relogin", true);
                    startActivityForResult(intent, 0x001);
                    return true;
                } else {
//                    view.loadUrl(url);
                    return super.shouldOverrideUrlLoading(view, url);
                }
//                return false;
            }

//            @Override
//            public void onReceivedSslError(WebView view,
//                                           SslErrorHandler handler, SslError error) {
//                // TODO Auto-generated method stub
//                // handler.cancel();// Android默认的处理方式
//                handler.proceed();// 接受所有网站的证书
//                // handleMessage(Message msg);// 进行其他处理
//            }
        });/*new WebViewClient() {

            @Override
            public void onLoadResource(WebView view, String url) {
                view.getUrl();
                Log.e("getUrl", view.getUrl());
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                view.getUrl();
                Log.e("getUrl", view.getUrl());
            }
        });*/

    }
    @Override
    public void onClick(View view) {
        super.onClick(view);
        switch (view.getId()) {
            case R.id.righticon:
                share();
                break;
/*            case R.id.baseback:
                //finish();
                break;*/
        }
    }
    String shareUrl;
    ShareDialog dialog;
    private void share() {
        if (dialog == null)
            dialog = new ShareDialog(this);
/*        imageUrl = "http://m.epfresh.com/images/icon.png";
        titleStr = "e批课堂开课啦！";
        description = "学用e批生鲜，采购轻松简单";*/

        if(shareUrl!=null&&!"".equals(shareUrl))
            dialog.showDialog(shareUrl, imageUrl, description, titleStr, null);
        else
            dialog.showDialog(url, imageUrl, description, titleStr, null);

    }


    @Override
    protected void onSaveInstanceState(Bundle outState) {
        if (outState == null) {
            outState = new Bundle();
        }
        outState.putString("share_web", shareUrl);
        outState.putString(Constant.KEY_WEB_URL, url);
        outState.putString(Constant.KEY_WEB_TITLE, title);
        outState.putInt("pushType", pushType);
        super.onSaveInstanceState(outState);
    }

    @Override
    public void onBackPressed() {
        if (webview.canGoBack()) {
            //finish();
            webview.goBack();
        } else if (pushType == 0) {
            Intent main = new Intent(getApplicationContext(), HomeActivity.class);
            startActivity(main);
            finish();
        } else if (pushType == 1) {
            finish();
        } else {
            super.onBackPressed();
        }
    }

    @Override
    protected void onDestroy() {
        if (webview != null) {
            webview.destroy();
        }
        super.onDestroy();
    }



    public void requestDc(boolean isSilent,String id) {

        RequestEntityMap re = new RequestEntityMap();
        re.setCmd(com.epfresh.api.constant.AppPurchaseRouterConstant.cmd_store_store_dcStore);
        re.putParameter("storeId",id);
        RequestTag requestTag = new RequestTag();
        requestTag.tag = com.epfresh.api.constant.AppPurchaseRouterConstant.cmd_store_store_dcStore;
        if (isSilent) {
            requestTag.type = RequestTag.TYPE_CURRENT;
            requestTag.arg1 = "silent";
            re.setCityId(ApplicationHelper.getInstance().getCity().getCityId());
            ApplicationHelper.getInstance().requestSilent(re, requestTag, onDetailRequestListener);
//                request(re, requestTag, onDetailRequestListener);
        } else {
            requestTag.arg1 = "1";
            request(re, requestTag, onDetailRequestListener);
        }

    }


    OnRequestListener<StoreDetail> onDetailRequestListener = new OnRequestListener<StoreDetail>() {
        @Override
        public StoreDetail jsonToObj(String s) {
            return new Gson().fromJson(s, StoreDetail.class);
        }

        @Override
        public void onFail(int i, Object o, Object o1) {

            if (o1 != null && o1 instanceof RequestTag) {
                RequestTag tag = (RequestTag) o1;
                if ("silent".equals(tag.arg1)) {

                } else {
                    hideProgressDialog();
                }
            } else {
                hideProgressDialog();
            }

        }

        @Override
        public void onResponseError(int i, Object o, Object o1) {

            if (o1 != null && o1 instanceof RequestTag) {
                RequestTag tag = (RequestTag) o1;
                if ("silent".equals(tag.arg1)) {

                } else {
                    hideProgressDialog();
                }
            } else {
                hideProgressDialog();
            }

        }

        @Override
        public void onStart(Object o1) {
            if (o1 != null && o1 instanceof RequestTag) {
                RequestTag tag = (RequestTag) o1;
                if ("silent".equals(tag.arg1)) {

                } else {
                    showProgressDialog();
                }
            } else {
                showProgressDialog();
            }

        }

        @Override
        public void onResponse(ResponseEntity<StoreDetail> responseEntity, Object o1) {

            StoreDetail responseElement = responseEntity.getResponseElement();
            if (responseElement != null) {

            }
            if (o1 != null && o1 instanceof RequestTag) {
                RequestTag tag = (RequestTag) o1;
                if ("silent".equals(tag.arg1)) {

                } else {
                    hideProgressDialog();
                    intoDcPage(responseElement);
                }
            } else {
                hideProgressDialog();
                intoDcPage(responseElement);
            }


        }
    };

    public void intoDcPage(StoreDetail responseElement) {
        if (responseElement != null) {

            if (!responseElement.isResult()) {
                Intent tv_more = new Intent(this,
                        CenterListActivity.class);
                startActivity(tv_more);
            } else {
                Intent tv_bulk_load = new Intent(this,
                        DcStoreActivity.class);
                tv_bulk_load.putExtra("data", new Gson().toJson(responseElement));
                startActivity(tv_bulk_load);
            }
        } else {

        }

    }


    /*openVideoLibrary 本地视频 takeVideo 选择视频 upload 上传 takePhoto 拍照 openAlbum 相册 loginData 登录信息 deviceInfo 设备信息 appCallBack 返回* */
    private Handler mHandler = new Handler();
    String h5Key = "";

    public class JsBridge {
        @JavascriptInterface
        public void callHandler(String functionName, String value, final String param3) {
            Log.e("functionName:", functionName + "-" + value + "-" + param3);
            h5Key = param3;
            if ("loginData".equals(functionName)) {
                final Map map = new ArrayMap();
                map.put("clientIdentifierCode", BaseApplication.getInstance().getClientIdentifierCode());
                map.put("token", BaseApplication.getInstance().getUser().getAccess_token());
                mHandler.post(new Runnable() {
                    public void run() {
                        evaluateJs("JSBridgeCallback('" + param3 + "'" + ",'" + new GsonBuilder().create().toJson(map) + "')");
                    }
                });
            }
            if ("deviceInfo".equals(functionName)) {
                final Map map = new ArrayMap();
                map.put("os", "android");
                map.put("osVersion", Build.VERSION.RELEASE);
                map.put("model", Build.MODEL);
                map.put("net", IntenetUtil.getNetworkState(WebCommonActivity.this));
                mHandler.post(new Runnable() {
                    public void run() {
                        evaluateJs("JSBridgeCallback('" + param3 + "'" + ",'" + new GsonBuilder().create().toJson(map) + "')");
                    }
                });
            }
            if ("getStoreInfo".equals(functionName)) {//todo: 采购端哪儿来的店铺信息？？？
                final Map map = new ArrayMap();
/*                map.put("storeType", ApplicationHelper.getInstance().getMerchant().getStoreCategoryType());
                map.put("storeName", ApplicationHelper.getInstance().getStoreName());*/
                mHandler.post(new Runnable() {
                    public void run() {
                        evaluateJs("JSBridgeCallback('" + param3 + "'" + ",'" + new GsonBuilder().create().toJson(map) + "')");
                    }
                });
            }

            if ("appCallBack".equals(functionName)) {//返回结束
                if (webview.canGoBack())
                    webview.goBack();
                //getActivity().finish();
            }

            if ("commodityDetail".equals(functionName)) {//商品详情 todo:新要求参数storeId
                JsBridgeValue jsBridgeValue = JsonUtils.fromJson(value, JsBridgeValue.class);
                if (jsBridgeValue != null)
                    intoProductDetail(jsBridgeValue.getProductId(), jsBridgeValue.getPromotionItemId());

            }

            if ("openLink".equals(functionName) || "openList".equals(functionName)) {//返回结束
                T.toast("openLink");
                //value:{"link":"https://www.baidu.com","title":"百度好吃的粉"}

                JsBridgeValue jsBridgeValue = JsonUtils.fromJson(value, JsBridgeValue.class);
                if (jsBridgeValue != null){
                    intoWebDetail(jsBridgeValue.getLink(),jsBridgeValue.getTitle());
                }
            }


        }
    }


    void intoWebDetail(String url, String title) {
        if (url == null || "".equals(url)) {
            return;
        }
        Intent intent = new Intent(this, WebCommonActivity.class);
        intent.putExtra(Constant.KEY_WEB_URL, url);
        intent.putExtra(Constant.KEY_WEB_TITLE, title);
        startActivity(intent);
    }

    void intoProductDetail(String productId, String promotionItemId) {
        if (productId == null || "".equals(productId)) {
            return;
        }
        Intent intent = new Intent(this, DetailGoodsActivity.class);

        intent.putExtra("id", productId + "");
        intent.putExtra("promotionItemId", promotionItemId);
        startActivity(intent);
    }


    @TargetApi(19)
    void evaluateJs(final String value) {
        Log.e("javascript", value.toString());
        final int version = Build.VERSION.SDK_INT;// 因为该方法在 Android 4.4 版本才可使用，所以使用时需进行版本判断
        if (version < 18) {
            webview.loadUrl(value);
        } else {
            webview.evaluateJavascript(value, new ValueCallback<String>() {
                @Override
                public void onReceiveValue(String value) {
                    //此处为 js 返回的结果
                }
            });
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 0x001 && resultCode == RESULT_OK) {
            if(getUser()!=null){
                url = shareUrl +"&phone="+getUser().getPhone()+"&token="+getUser().getAccess_token()+"&cid=" + AppUtils.getUniquePsuedoID();
                Log.e("after login url___",url);

            }
            Log.e("after login url_error__",url);
            webview.clearHistory();
            if(url.contains("?")){
                webview.loadUrl(url+"&oc=android");
            }else{
                webview.loadUrl(url+"?oc=android");
            }
            Log.e("clear",url);
        }
    }
}
